<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataId ? '编辑' : '新增'}-质量模版`"
		width="800px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn('save')"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" :show-message="false">
			<el-row ref="box1">
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="模版名称" prop="name">
						<jk-input v-model="ruleForm.name" class="width-100-percent" placeholder="模版名称"></jk-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="检验类型" prop="typeId">
						<el-select v-model="ruleForm.typeId" class="width-100-percent" placeholder="检验类型" @change="onExamineListChange">
							<el-option
								v-for="item in examineList"
								:key="item.id"
								:label="item.name"
								:value="item.id"
							></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="排序">
						<jk-number-input v-model="ruleForm.sortNum" class="width-100-percent"></jk-number-input>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<jk-table border :data="ruleForm.itemList" :height="dialogTableHeight - 20">
			<vxe-column title="操作" align="center" field="processName" :width="120">
				<template slot="header">
					<el-button type="text" size="mini" @click="onAddBtn">添加</el-button>
				</template>
				<template slot-scope="scope">
					<div class="flex-center">
						<jk-button type="default" class="item-gap" icon="el-icon-plus" size="mini" @click="ruleForm.itemList.push({})"></jk-button>
						<jk-button type="default" icon="el-icon-minus" size="mini" @click="ruleForm.itemList.splice(scope.rowIndex, 1)"></jk-button>
					</div>
				</template>
			</vxe-column>
			<vxe-column title="序号" type="seq" align="center" :width="80"> </vxe-column>
			<vxe-column title="指标" align="left" field="qualityItemName" :width="160">
				<template slot-scope="scope">
					<el-input v-model="scope.row.qualityItemName" size="mini"></el-input>
				</template>
			</vxe-column>
		</jk-table>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import checkboxMachineDialog from '../../schedule/empMachine/components/checkbox-machine-dialog';
    import {
        spinQualityInspectionModelCreate, spinQualityInspectionModelGet,
        spinQualityInspectionModelUpdate,
        systemBusinessDictPage
    } from '../../../api/quality/processQuality';
    import { spinQualityIndexPage } from '../../../api/quality/processQualityItems';
    export default {
        components: {
            checkboxMachineDialog
        },
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            defaultTypeCode: {
                type: String,
                default: ''
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data: function() {
            return {
                selectMachineDialogState: false,
                workshopList: [],
                examineList: [],
                processList: [],
                targetList: [
                    { id: 1, qualityItemName: '条干' },
                    { id: 2, qualityItemName: '重量' },
                    { id: 3, qualityItemName: '棉结' }
                ],
                showDialog: false,
                showLoading: true,
                saveBtnLoading: false,
                ruleForm: {
                    sortNum: 0,
                    id: null,
                    code: '',
                    name: '',
                    workshopId: null,
                    typeId: '',
                    typeName: '',
                    typeCode: '',
                    itemList: []
                },
                rules: {
                    name: [{ required: true, trigger: 'change' }],
                    typeId: [{ required: true, trigger: 'change' }]
                },
                selectRowIndex: null,
                selectRowMachineList: []
            };
        },
        methods: {
            onExamineListChange(e) {
                this.examineList.forEach(x => {
                    if (e === x.id) {
                        this.$set(this.ruleForm, 'typeName', x.name);
                        this.$set(this.ruleForm, 'typeCode', x.code);
                    }
                });
            },
            onAddBtn() {
                this.ruleForm.itemList.push({});
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) delete params.id;
                return params;
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                const api = !this.dataId ? spinQualityInspectionModelCreate : spinQualityInspectionModelUpdate;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onConfirmBtn(type) {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return spinQualityInspectionModelGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                    }
                });
            },
            getTypeListRequest() {
                const params = {
                    categoryCode: 'QUALITY_TYPE',
                    pageSize: 100,
                    pageNo: 1
                };
                return systemBusinessDictPage(params).then(res => {
                    if (res.data.status === 200) {
                        this.examineList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.processList = this.$store.state.user.userProcess.processList;
                await this.getTypeListRequest();
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
